#!/bin/bash
# ThingsBoard 备份保留策略脚本
# 版本: 1.0.0

# 设置脚本名称
SCRIPT_NAME="retention"

# 记录当前工作目录
CURRENT_DIR=$(pwd)

# 获取脚本所在目录的绝对路径
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)

# 根据脚本目录计算项目根目录路径
if [[ "$SCRIPT_DIR" == */scripts/backup ]]; then
  # 如果脚本位于scripts/backup目录中
  PROJECT_ROOT=$(cd "$SCRIPT_DIR/../.." && pwd)
elif [[ "$SCRIPT_DIR" == */scripts/* ]]; then
  # 如果脚本位于scripts目录或其他子目录中
  PROJECT_ROOT=$(echo "$SCRIPT_DIR" | sed 's|\(.*\)/scripts.*|\1|')
else
  # 否则假设当前目录是项目根目录
  PROJECT_ROOT=$(pwd)
fi

# 配置文件路径
CONFIG_FILE="$PROJECT_ROOT/config/backup_env.conf"

# 检查配置文件是否存在
if [ ! -f "$CONFIG_FILE" ]; then
  echo "错误: 配置文件不存在: $CONFIG_FILE"
  exit 1
fi

# 导入共用函数 - 使用绝对路径
COMMON_SCRIPT="$PROJECT_ROOT/scripts/common.sh"
if [ -f "$COMMON_SCRIPT" ]; then
  source "$COMMON_SCRIPT"
else
  echo "错误: 共用脚本不存在: $COMMON_SCRIPT"
  exit 1
fi

log_info "开始执行备份保留策略清理..."

# 检查环境
check_environment

# 步骤1：验证备份保留参数
step=$(next_step)
log_info "验证备份保留参数..." "$step"

if [ -z "$FULL_BACKUP_RETAIN_DAYS" ] || [ "$FULL_BACKUP_RETAIN_DAYS" -lt 1 ]; then
    handle_error 1 "全量备份保留天数(FULL_BACKUP_RETAIN_DAYS)参数无效：$FULL_BACKUP_RETAIN_DAYS" "$step"
fi

if [ -z "$DIFF_BACKUP_RETAIN_DAYS" ] || [ "$DIFF_BACKUP_RETAIN_DAYS" -lt 1 ]; then
    handle_error 2 "增量备份保留天数(DIFF_BACKUP_RETAIN_DAYS)参数无效：$DIFF_BACKUP_RETAIN_DAYS" "$step"
fi

if [ -z "$WAL_RETAIN_DAYS" ] || [ "$WAL_RETAIN_DAYS" -lt 1 ]; then
    handle_error 3 "WAL日志保留天数(WAL_RETAIN_DAYS)参数无效：$WAL_RETAIN_DAYS" "$step"
fi

log_success "备份保留参数验证通过" "$step"

# 步骤2：创建WAL-G配置
step=$(next_step)
log_info "创建WAL-G配置..." "$step"

# 创建MinIO S3配置文件
cat > "/root/.walg.json" <<EOF
{
  "WALG_S3_PREFIX": "s3://${MINIO_BUCKET}/${MINIO_FULL_PREFIX}",
  "AWS_ACCESS_KEY_ID": "${MINIO_USER}",
  "AWS_SECRET_ACCESS_KEY": "${MINIO_PASSWORD}",
  "AWS_ENDPOINT": "http://${MINIO_HOST}:${MINIO_PORT}",
  "AWS_S3_FORCE_PATH_STYLE": "true",
  "PGHOST": "localhost",
  "PGPORT": "5432",
  "PGUSER": "$POSTGRES_SUPERUSER",
  "PGPASSWORD": "$POSTGRES_PASSWORD",
  "PGDATABASE": "$THINGSBOARD_DATABASE_NAME",
  "WALG_COMPRESSION_METHOD": "lz4"
}
EOF

# 设置环境变量
export WALG_S3_PREFIX="s3://${MINIO_BUCKET}/${MINIO_FULL_PREFIX}"
export AWS_ACCESS_KEY_ID="${MINIO_USER}"
export AWS_SECRET_ACCESS_KEY="${MINIO_PASSWORD}"
export AWS_ENDPOINT="http://${MINIO_HOST}:${MINIO_PORT}"
export AWS_S3_FORCE_PATH_STYLE="true"
export PGHOST=localhost
export PGPORT=5432
export PGUSER=$POSTGRES_SUPERUSER
export PGPASSWORD=$POSTGRES_PASSWORD
export WALG_COMPRESSION_METHOD=lz4

log_success "WAL-G配置创建完成" "$step"

# 步骤3：清理过期的全量备份
step=$(next_step)
log_info "清理过期的全量备份（保留${FULL_BACKUP_RETAIN_DAYS}天）..." "$step"

RETAIN_FULL="$(which wal-g) delete retain FULL $FULL_BACKUP_RETAIN_DAYS --confirm"
if [ $? -ne 0 ]; then
    handle_error 4 "清理过期全量备份失败" "$step"
fi

log_success "过期全量备份清理完成" "$step"

# 步骤4：清理过期的增量备份
step=$(next_step)
log_info "清理过期的增量备份（保留${DIFF_BACKUP_RETAIN_DAYS}天）..." "$step"

# 临时切换到增量备份目录
export WALG_S3_PREFIX="s3://${MINIO_BUCKET}/${MINIO_DIFF_PREFIX}"

RETAIN_DIFF="$(which wal-g) delete retain FULL $DIFF_BACKUP_RETAIN_DAYS --confirm"
if [ $? -ne 0 ]; then
    handle_error 5 "清理过期增量备份失败" "$step"
fi

log_success "过期增量备份清理完成" "$step"

# 步骤5：清理过期的WAL日志
step=$(next_step)
log_info "清理过期的WAL日志（保留${WAL_RETAIN_DAYS}天）..." "$step"

RETAIN_WAL="$(which wal-g) delete retain WAL $WAL_RETAIN_DAYS --confirm"
if [ $? -ne 0 ]; then
    handle_error 6 "清理过期WAL日志失败" "$step"
fi

log_success "过期WAL日志清理完成" "$step"

# 步骤6：备份整理完成
step=$(next_step)
log_info "备份保留策略执行完成" "$step"

# 打印保留策略信息
log_info "全量备份保留天数: $FULL_BACKUP_RETAIN_DAYS" "$step"
log_info "增量备份保留天数: $DIFF_BACKUP_RETAIN_DAYS" "$step"
log_info "WAL日志保留天数: $WAL_RETAIN_DAYS" "$step"

# 列出当前备份状态
log_info "当前全量备份状态:" "$step"
export WALG_S3_PREFIX="s3://${MINIO_BUCKET}/${MINIO_FULL_PREFIX}"
FULL_BACKUPS=$($(which wal-g) backup-list 2>/dev/null || echo "无法获取全量备份列表")
log_info "$FULL_BACKUPS" "$step"

log_info "当前增量备份状态:" "$step"
export WALG_S3_PREFIX="s3://${MINIO_BUCKET}/${MINIO_DIFF_PREFIX}"
DIFF_BACKUPS=$($(which wal-g) backup-list 2>/dev/null || echo "无法获取增量备份列表")
log_info "$DIFF_BACKUPS" "$step"

log_success "备份保留策略清理完成" "最终"
exit 0
